package handlers

import (
	"github.com/gofiber/fiber/v2"
	"notabug.org/alimiracle/my-website-api/models"
	"notabug.org/alimiracle/my-website-api/responses"
)

func (self Handler) GetAllContacts(c *fiber.Ctx) error {
	var contacts []models.Contact

	self.Database.FindAll(&contacts)
	return c.Status(fiber.StatusOK).JSON(&contacts)
}

func (self Handler) AddContact(c *fiber.Ctx) error {
	body := models.Contact{}
	if err := c.BodyParser(&body); err != nil {
		return responses.BadRequestResponse(c, err)

	}

	// insert new db entry
	err := self.Database.Create(&body)
	if err != nil {
		return fiber.NewError(fiber.StatusNotFound, err.Error())

	}
	return c.Status(fiber.StatusCreated).JSON(&body)
}
func (self Handler) UpdateContact(c *fiber.Ctx) error {
	id := c.Params("id")
	body := models.Contact{}
	if err := c.BodyParser(&body); err != nil {
		return responses.BadRequestResponse(c, err)

	}
	err := self.Database.Update(&body, id)
	if err != nil {
		return fiber.NewError(fiber.StatusNotFound, err.Error())
	}
	return c.SendStatus(fiber.StatusOK)
}
func (self Handler) DeleteContact(c *fiber.Ctx) error {
	id := c.Params("id")

	var contact models.Contact

	err := self.Database.Delete(&contact, id)
	if err != nil {
		return fiber.NewError(fiber.StatusNotFound, err.Error())

	}
	return c.SendStatus(fiber.StatusOK)
}
